package com.ssy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssy.bus.pojo.Department;
import com.ssy.bus.service.IDepartmentService;
import com.ssy.common.CodeMsg;
import com.ssy.common.Constant;
import com.ssy.common.utils.MD5Utils;
import com.ssy.common.utils.PageResult;
import com.ssy.common.utils.Result;
import com.ssy.system.mapper.UserMapper;
import com.ssy.system.pojo.CommonType;
import com.ssy.system.pojo.User;
import com.ssy.system.service.ICommonTypeService;
import com.ssy.system.service.IUserService;
import com.ssy.system.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ssy
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ICommonTypeService commonTypeService;

    @Autowired
    private IDepartmentService departmentService;

    @Override
    public PageResult queryAllUserByPage(UserVo userVo) {
        Page<User> page = new Page<>(userVo.getPage(), userVo.getLimit());
        IPage<User> userPage = this.userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                .eq(userVo.getDepId() != null, User::getDepId, userVo.getDepId())
                .like(StringUtils.hasText(userVo.getUserName()), User::getUserName, userVo.getUserName())
                .like(StringUtils.hasText(userVo.getPhone()), User::getPhone, userVo.getPhone())
                .eq(userVo.getState() != null, User::getState, userVo.getState())
                .ge(userVo.getBeginTime() != null, User::getCreateTime, userVo.getBeginTime())
                .le(userVo.getEndTime() != null, User::getCreateTime, userVo.getEndTime())
                .notIn(User::getType, Constant.USER_TYPE_SUPER)
                .orderByDesc(User::getCreateTime));

        List<User> userList = userPage.getRecords();
        for (User user : userList) {
            Integer typeId = user.getType();
            if (typeId != null) {
                CommonType commonType = this.commonTypeService.queryCommonTypeById(typeId);
                user.setUserTypeName(commonType.getName());
            }

            Integer levelId = user.getLevel();
            if (levelId != null) {
                CommonType commonType = this.commonTypeService.queryCommonTypeById(levelId);
                user.setLevelName(commonType.getName());
            }

            Integer depId = user.getDepId();
            if (depId != null) {
                Department department = this.departmentService.queryDepartmentById(depId);
                user.setDepName(department.getName());
            }

        }
        return new PageResult(userPage.getTotal(), userList);
    }


    @Override
    public Result insertUser(User user) {
        if (user == null) {
            return new Result(CodeMsg.ADD_ERROR);
        }

        //用户名校验
        List<User> userList = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, user.getUserName()));
        if (userList.size() > 0) {
            return new Result(CodeMsg.ADD_USER_NAME_ERROR);
        }

        //手机号校验
        List<User> userList2 = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, user.getPhone()));
        if (userList2.size() > 0) {
            return new Result(CodeMsg.ADD_USER_PHONE_ERROR);
        }

        int i = this.userMapper.insert(user);
        return i > 0 ? new Result(CodeMsg.ADD_SUCCESS) : new Result(CodeMsg.ADD_ERROR);
    }

    @Override
    public Result deleteUserById(Integer id) {
        if (id == null) {
            return new Result(CodeMsg.DELETE_ERROR);
        }
        int i = this.userMapper.deleteById(id);
        return i > 0 ? new Result(CodeMsg.DELETE_SUCCESS) : new Result(CodeMsg.DELETE_ERROR);
    }

    @Override
    public Result bathDeleteUser(Integer[] ids) {
        if (ids == null && ids.length == 0) {
            return new Result(CodeMsg.DELETE_ERROR);
        }
        ArrayList<Serializable> idList = new ArrayList<>();
        for (Integer id : ids) {
            idList.add(id);
        }
        int i = this.userMapper.deleteBatchIds(idList);
        return i > 0 ? new Result(CodeMsg.DELETE_SUCCESS) : new Result(CodeMsg.DELETE_ERROR);
    }

    @Override
    public Result updateUserById(User user) {
        if (user == null) {
            return new Result(CodeMsg.UPDATE_ERROR);
        }

        //用户名校验
        List<User> userList = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, user.getUserName())
                .notIn(User::getId, Arrays.asList(user.getId())));
        if (userList.size() > 0) {
            return new Result(CodeMsg.ADD_USER_NAME_ERROR);
        }

        //手机号校验
        List<User> userList2 = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, user.getPhone())
                .notIn(User::getId, Arrays.asList(user.getId()))
        );
        if (userList2.size() > 0) {
            return new Result(CodeMsg.ADD_USER_PHONE_ERROR);
        }

        int i = this.userMapper.updateById(user);
        return i > 0 ? new Result(CodeMsg.UPDATE_SUCCESS) : new Result(CodeMsg.UPDATE_ERROR);
    }

    @Override
    public Result resetUserPwdById(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return new Result(CodeMsg.RESET_USER_PASSWORD_ERROR);
        }

        for (Integer id : ids) {
            User user = new User();
            String salt = MD5Utils.getSalt();
            user.setSalt(salt);
            user.setId(id);
            user.setPassword(MD5Utils.md5(Constant.USER_DEFAULT_PASSWORD, salt, 4));
            this.userMapper.updateById(user);
        }
        return new Result(CodeMsg.RESET_USER_PASSWORD_SUCCESS);
    }

    @Override
    public Result insertRoleUser(Integer userId, Integer[] ids) {
        this.userMapper.deleteRoleUserByRid(userId);
        if (ids == null || ids.length == 0) {
            return new Result(CodeMsg.DISTRIBUTION_USER_ROLE_ERROR);
        }
        for (Integer id : ids) {
            this.userMapper.insertRoleUser(userId, id);
        }
        return new Result(CodeMsg.DISTRIBUTION_USER_ROLE_SUCCESS);
    }

    @Override
    public User QueryUserByUserName(String userName) {
        if (!StringUtils.hasText(userName)) {
            return null;
        }
        return this.userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getState, 1)
                .eq(User::getUserName, userName));
    }

    @Override
    public int updateUserPwdById(User user) {
        return this.userMapper.updateById(user);
    }
}
